<template>
  <div class="project-detail">
    <ContentWrap>
      <!-- 页面头部 -->
      <div class="detail-header">
        <el-button @click="goBack" class="back-btn">
          <Icon icon="ep:arrow-left" />返回
        </el-button>
        <div class="header-info">
          <h1>{{ projectInfo.name }}</h1>
          <p>{{ projectInfo.description }}</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="editProject">
            <Icon icon="ep:edit" />编辑项目
          </el-button>
          <el-button type="success" @click="exportProject">
            <Icon icon="ep:download" />导出资料
          </el-button>
          <el-button type="info" @click="openCodeUrl" v-if="projectInfo.codeUrl">
            <Icon icon="ep:link" />查看代码
          </el-button>
        </div>
      </div>

      <!-- 项目基本信息和资料统计 -->
      <el-row :gutter="30" class="info-section" v-loading="loading">
        <el-col :span="16">
          <el-card class="info-card" shadow="never">
            <template #header>
              <div class="card-header">
                <Icon icon="ep:info-filled" />
                <span>项目信息</span>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="项目名称">{{ projectInfo.name }}</el-descriptions-item>
              <el-descriptions-item label="项目版本">{{ projectInfo.version || '-' }}</el-descriptions-item>
              <el-descriptions-item label="项目负责人">{{ projectInfo.manager || '-' }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDate(projectInfo.createTime) }}</el-descriptions-item>
              <el-descriptions-item label="开始日期">{{ projectInfo.startDate || '-' }}</el-descriptions-item>
              <el-descriptions-item label="截止日期">{{ projectInfo.deadline || '-' }}</el-descriptions-item>
              <el-descriptions-item label="存活状态">
                <dict-tag :type="DICT_TYPE.AGENT_PROJECT_STATUS" :value="projectInfo.status" />
              </el-descriptions-item>
              <el-descriptions-item label="进行状态">
                <dict-tag :type="DICT_TYPE.AGENT_PROJECT_PROGRESS_STATUS" :value="projectInfo.progressStatus" />
              </el-descriptions-item>
              <el-descriptions-item label="资料总数">{{ totalMaterialCount }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDate(projectInfo.updateTime) }}</el-descriptions-item>
              <el-descriptions-item label="项目描述" :span="2">{{ projectInfo.description || '-' }}</el-descriptions-item>
              <el-descriptions-item label="代码地址" :span="2" v-if="projectInfo.codeUrl">
                <el-link :href="projectInfo.codeUrl" target="_blank" type="primary">{{ projectInfo.codeUrl }}</el-link>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="stats-card" shadow="never">
            <template #header>
              <div class="card-header">
                <Icon icon="ep:data-line" />
                <span>资料统计</span>
              </div>
            </template>
            <div class="stats-grid">
              <div class="stat-item content" @click="handleAddMaterial('content')">
                <div class="stat-icon">
                  <Icon icon="ep:document" />
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ projectInfo.contentCount || 0 }}</div>
                  <div class="stat-label">内容资料</div>
                </div>
                <div class="stat-action">
                  <Icon icon="ep:plus" />
                </div>
              </div>
              <div class="stat-item resource" @click="handleAddMaterial('resource')">
                <div class="stat-icon">
                  <Icon icon="ep:folder" />
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ projectInfo.resourceCount || 0 }}</div>
                  <div class="stat-label">项目资料</div>
                </div>
                <div class="stat-action">
                  <Icon icon="ep:plus" />
                </div>
              </div>
              <div class="stat-item meeting" @click="handleAddMaterial('meeting')">
                <div class="stat-icon">
                  <Icon icon="ep:chat-dot-round" />
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ projectInfo.meetingCount || 0 }}</div>
                  <div class="stat-label">会议记录</div>
                </div>
                <div class="stat-action">
                  <Icon icon="ep:plus" />
                </div>
              </div>
              <div class="stat-item technical" @click="handleAddMaterial('technical')">
                <div class="stat-icon">
                  <Icon icon="ep:cpu" />
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ projectInfo.technicalCount || 0 }}</div>
                  <div class="stat-label">技术文档</div>
                </div>
                <div class="stat-action">
                  <Icon icon="ep:plus" />
                </div>
              </div>
              <div class="stat-item document" @click="handleAddMaterial('document')">
                <div class="stat-icon">
                  <Icon icon="ep:document-copy" />
                </div>
                <div class="stat-info">
                  <div class="stat-number">{{ projectInfo.documentCount || 0 }}</div>
                  <div class="stat-label">其他文档</div>
                </div>
                <div class="stat-action">
                  <Icon icon="ep:plus" />
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 资料分类管理 -->
      <div class="materials-section">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="内容资料" name="content">
            <MaterialList
              :materials="materialsList"
              :loading="materialsLoading"
              category="content"
              @add="handleAddMaterial"
              @edit="handleEditMaterial"
              @delete="handleDeleteMaterial"
              @download="handleDownloadMaterial"
              @batch-upload="handleBatchUpload"
            />
          </el-tab-pane>

          <el-tab-pane label="项目资料" name="resource">
            <MaterialList
              :materials="materialsList"
              :loading="materialsLoading"
              category="resource"
              @add="handleAddMaterial"
              @edit="handleEditMaterial"
              @delete="handleDeleteMaterial"
              @download="handleDownloadMaterial"
              @batch-upload="handleBatchUpload"
            />
          </el-tab-pane>

          <el-tab-pane label="会议记录" name="meeting">
            <MaterialList
              :materials="materialsList"
              :loading="materialsLoading"
              category="meeting"
              @add="handleAddMaterial"
              @edit="handleEditMaterial"
              @delete="handleDeleteMaterial"
              @download="handleDownloadMaterial"
              @batch-upload="handleBatchUpload"
            />
          </el-tab-pane>

          <el-tab-pane label="技术文档" name="technical">
            <MaterialList
              :materials="materialsList"
              :loading="materialsLoading"
              category="technical"
              @add="handleAddMaterial"
              @edit="handleEditMaterial"
              @delete="handleDeleteMaterial"
              @download="handleDownloadMaterial"
              @batch-upload="handleBatchUpload"
            />
          </el-tab-pane>

          <el-tab-pane label="其他文档" name="document">
            <MaterialList
              :materials="materialsList"
              :loading="materialsLoading"
              category="document"
              @add="handleAddMaterial"
              @edit="handleEditMaterial"
              @delete="handleDeleteMaterial"
              @download="handleDownloadMaterial"
              @batch-upload="handleBatchUpload"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </ContentWrap>

    <!-- 项目表单 -->
    <ProjectForm ref="formRef" @success="loadProjectDetail" />

    <!-- 资料上传组件 -->
    <ProjectMaterialUpload ref="uploadRef" @success="handleUploadSuccess" />

    <!-- 批量上传组件 -->
    <ProjectMaterialBatchUpload ref="batchUploadRef" @success="handleUploadSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ManageProjectApi, type ManageProjectVO } from '@/api/agent/manage/manageProject'
import { MaterialApi, type MaterialVO } from '@/api/agent/manage/material'
import { DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import MaterialList from '../components/MaterialList.vue'
import ProjectForm from './ProjectForm.vue'
import ProjectMaterialUpload from './ProjectMaterialUpload.vue'
import ProjectMaterialBatchUpload from './ProjectMaterialBatchUpload.vue'

defineOptions({ name: 'ProjectDetail' })

const router = useRouter()
const route = useRoute()
const message = useMessage()
const { t } = useI18n()

// 加载状态
const loading = ref(true)
const materialsLoading = ref(false)

// 项目信息
const projectInfo = ref<ManageProjectVO>({
  id: undefined,
  name: '',
  description: '',
  manager: '',
  version: '',
  status: '',
  progressStatus: '',
  progress: 0,
  startDate: '',
  deadline: '',
  codeUrl: '',
  contentCount: 0,
  resourceCount: 0,
  meetingCount: 0,
  technicalCount: 0,
  documentCount: 0
})

// 资料列表
const materialsList = ref<MaterialVO[]>([])

// 当前激活的标签页
const activeTab = ref('content')

// 计算属性
const totalMaterialCount = computed(() => {
  return (
    (projectInfo.value.contentCount || 0) +
    (projectInfo.value.resourceCount || 0) +
    (projectInfo.value.meetingCount || 0) +
    (projectInfo.value.technicalCount || 0) +
    (projectInfo.value.documentCount || 0)
  )
})

// 方法定义
const goBack = () => {
  router.go(-1)
}

/** 加载项目详情 */
const loadProjectDetail = async () => {
  const projectId = route.params.id as string
  if (!projectId) {
    message.error('项目ID不存在')
    goBack()
    return
  }

  loading.value = true
  try {
    const data = await ManageProjectApi.getManageProject(Number(projectId))
    projectInfo.value = data
  } catch (error) {
    console.error('加载项目详情失败:', error)
    message.error('加载项目详情失败')
  } finally {
    loading.value = false
  }
}

/** 加载资料列表 */
const loadMaterialsList = async (category: string) => {
  const projectId = route.params.id as string
  if (!projectId) return
  materialsLoading.value = true
  try {
    const params = {
      relatedId: Number(projectId),
      relatedType: 'project',
      category: category
    }
    const data = await MaterialApi.getMaterialPage(params)
    materialsList.value = data.list || []
  } catch (error) {
    console.error('加载资料列表失败:', error)
    materialsList.value = []
  } finally {
    materialsLoading.value = false
  }
}

const formRef = ref()
const editProject = () => {
  formRef.value.open('update', projectInfo.value.id)
}

const exportProject = () => {
  message.success('导出功能开发中...')
}

const openCodeUrl = () => {
  if (projectInfo.value.codeUrl) {
    window.open(projectInfo.value.codeUrl, '_blank')
  }
}

const handleTabClick = (tab: any) => {
  // Element Plus的tab-click事件参数结构
  const tabName = tab.paneName || tab.name
  activeTab.value = tabName
  loadMaterialsList(tabName)
}

const uploadRef = ref()
const handleAddMaterial = (category: string) => {
  const projectId = Number(route.params.id)
  uploadRef.value.open(category, projectId)
}

// 批量上传 - 现在从MaterialList组件触发
const batchUploadRef = ref()
const handleBatchUpload = (category: string) => {
  const projectId = Number(route.params.id)
  const version = projectInfo.value.version || 'v1.0.0'
  batchUploadRef.value.open(category, projectId, version)
}

// 在 handleEditMaterial 方法中修改：
const handleEditMaterial = (material: MaterialVO) => {
  uploadRef.value.openEdit(material)
}

const handleDeleteMaterial = async (material: MaterialVO) => {
  try {
    await message.delConfirm()
    await MaterialApi.deleteMaterial(material.id!)
    message.success('删除成功')

    // 重新加载资料列表和项目详情
    await loadMaterialsList(activeTab.value)
    await loadProjectDetail()
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除资料失败:', error)
    message.error('删除资料失败')
  }
}

const handleDownloadMaterial = (material: MaterialVO) => {
  if (material.fileUrl) {
    window.open(material.fileUrl, '_blank')
  } else {
    message.warning('文件地址不存在')
  }
}

const handleUploadSuccess = async () => {
  // 重新加载资料列表和项目详情
  await loadMaterialsList(activeTab.value)
  await loadProjectDetail()
}

// 初始化
onMounted(async () => {
  await loadProjectDetail()
  await loadMaterialsList(activeTab.value)
})
</script>

<style lang="scss" scoped>
.project-detail {
  .detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px;

    .back-btn {
      background: rgba(255, 255, 255, 0.2);
      border: none;
      color: white;

      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }

    .header-info {
      flex: 1;
      text-align: center;

      h1 {
        margin: 0 0 8px 0;
        font-size: 28px;
        font-weight: 600;
      }

      p {
        margin: 0;
        opacity: 0.9;
        font-size: 16px;
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;

      .el-button {
        background: rgba(255, 255, 255, 0.2);
        border: none;
        color: white;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
        }
      }
    }
  }

  .info-section {
    margin-bottom: 30px;
  }

  .info-card,
  .stats-card {
    .card-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #303133;
    }
  }

  .stats-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;

    .stat-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border-radius: 8px;
      transition: all 0.3s;
      cursor: pointer;
      position: relative;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

        .stat-action {
          opacity: 1;
        }
      }

      .stat-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        font-size: 18px;
        color: white;
      }

      .stat-info {
        flex: 1;

        .stat-number {
          font-size: 24px;
          font-weight: 600;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 12px;
          color: #666;
        }
      }

      .stat-action {
        position: absolute;
        top: 8px;
        right: 8px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.9);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s;
        font-size: 12px;
        color: #409eff;
      }

      &.content {
        background: rgba(64, 158, 255, 0.1);
        .stat-icon {
          background: #409eff;
        }
        .stat-number {
          color: #409eff;
        }
      }

      &.resource {
        background: rgba(103, 194, 58, 0.1);
        .stat-icon {
          background: #67c23a;
        }
        .stat-number {
          color: #67c23a;
        }
      }

      &.meeting {
        background: rgba(230, 162, 60, 0.1);
        .stat-icon {
          background: #e6a23c;
        }
        .stat-number {
          color: #e6a23c;
        }
      }

      &.technical {
        background: rgba(245, 108, 108, 0.1);
        .stat-icon {
          background: #f56c6c;
        }
        .stat-number {
          color: #f56c6c;
        }
      }

      &.document {
        background: rgba(144, 147, 153, 0.1);
        .stat-icon {
          background: #909399;
        }
        .stat-number {
          color: #909399;
        }
      }
    }
  }

  .materials-section {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}
</style>